package com.whz.iplocation.configure;

import com.whz.iplocation.ipregion.search.ByteIPLocation;
import com.whz.iplocation.ipregion.search.db.IpDataLoader;
import com.whz.generic.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @author whz
 */
@Slf4j
@EnableScheduling
@Configuration
public class IpLocationConfiguration {
    @Bean
    public ByteIPLocation createByteIPLocation() {
        byte[] d = IpDataLoader.DEFAULT_LOADER.getDataBase();
        return ByteIPLocation.locate(d);
    }

    @Scheduled(cron = "${generic.ip.location.auto.update.days:5}")
    public void schedule() {
        SpringUtils.getBean(ByteIPLocation.class).ifPresent(ip -> {
            byte[] d = IpDataLoader.DEFAULT_LOADER.getDataBase();
            ip.updateData(d);
            log.info("自动更新IP定位服务元数据.");
        });
    }
}